package shark.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import shark.auth.detail.SysUserDetails;
import shark.user.service.ISysRoleService;
import shark.user.service.ISysUserService;
import shark.user.spi.entity.SysRole;
import shark.user.spi.entity.SysUser;
import shark.user.spi.mapper.SysUserMapper;
import shark.user.spi.mapper.SysUserRoleMapper;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SharkUserDetailService implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser sysUser = userMapper.selectOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUsername, s));

        if (sysUser != null) {
            SysUserDetails sysUserDetails = new SysUserDetails();
            BeanUtils.copyProperties(sysUser, sysUserDetails);

            Set<GrantedAuthority> authorities = new HashSet<>(); // 角色集合
            List<String> roleList = userRoleMapper.getRoleByUserName(s);

            roleList.forEach(role -> {
                authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
            });

            sysUserDetails.setAuthorities(authorities);
            return  sysUserDetails;
        } else {
            throw new UsernameNotFoundException("该用户不存在！");
        }
    }
}
